import React, { Component } from 'react';
import { Button, message, Row, Col, Input } from 'antd';
import MenuList from './list';
import Modal from '../../../components/Modal/index';
import MenuAdd from './add';
import services from '../../../services/api';

const { Search } = Input;

class MenuConfig extends Component {
  constructor(props) {
    super(props);
    this.api = 'menu';
    this.state = {
      menu: [],
      searchName: '',
      expandedRowKeys: []
    };
    this.model_width = 500;
    this.menuAll = [] // 原始全部数据
    this.menuArr = [] // 打平的原始全部数据
    this.filters = []
  }
  componentDidMount() {
    this.freshQueryList();
  }

  freshQueryList = () => {
    this.queryList();
  };

  refreshFilter = () => {
    this.freshQueryList();
  };

  // 将数据平铺，便于搜索
  generateList = (data, path, list) => {
    for (let i = 0; i < data.length; i++) {
      const key = path === undefined ? '' + data[i].id : path + '-' + data[i].id;
      const children = data[i].children
      const treeNode = {
        title: data[i].name,
        key,
      };
      list.push(treeNode);
      if (children && children.length > 0) {
        this.generateList(children, key, list);
      }
    }
    return list;
  };

  searchChange = (value) => {
    let filterArr = []
    let expandArr = []
    if (value) {
      this.menuArr.forEach(item => {
        if (item.title.indexOf(value) > -1) {
          const arr = (this.getParentKey(item.key)).map(Number)
          expandArr = [...expandArr,  ...(arr.slice(0, arr.length - 1))]
          filterArr = [...filterArr,  ...arr]
        }
      })
    }
    expandArr = Array.from(new Set(expandArr))
    if (value && expandArr.length === 0) {
      this.setState({
        menu: [],
        searchName: value,
        expandedRowKeys: []
      })
    } else {
      this.filters = Array.from(new Set(filterArr))
      const newMenu = this.filterMenu(this.menuAll, this.filters)
      this.setState({
        menu: newMenu,
        searchName: value,
        expandedRowKeys: expandArr
      })
    }
  }
  
  getParentKey = (key) => {
    let arr = key.split('-')
    return arr
  };

  filterMenu = (menu, filters) => {
    if (filters.length === 0) {
      return menu
    } else {
      return (menu.filter(item => {
        return filters.indexOf(item.id) > -1
      }).map(item => {
        item = Object.assign({}, item)
        if (item.children) {
            item.children = this.filterMenu(item.children, filters)
            if (item.children.length === 0) item.children = null
        }
        return item
      }))
    }
  }

  queryList = () => {
    services[this.api].list({}).then(data => {
      if (data.code === 0) {
        this.menuAll = [data.data.root]
        this.menuArr = this.generateList([data.data.root], undefined, [])
        this.searchChange(this.state.searchName)
      } else {
        message.error(data.msg);
      }
    });
  };

  add = () => {
    Modal.open({
      title: '新增',
      width: '500px',
      content: <MenuAdd closeModal={this.closeModal} actionType='add' treeData={this.props.menu} />,
      isOkBtn: false,
      isCancelBtn: false
    });
  };

  edit = record => {
    Modal.open({
      title: '编辑',
      width: '500px',
      content: <MenuAdd closeModal={this.closeModal} actionType='update' treeData={this.props.menu} record={record} />,
      isOkBtn: false,
      isCancelBtn: false
    });
  };

  closeModal = () => {
    Modal.close();
    this.queryList();
  };

  render() {
    return (
      <div>
        <Row type='flex' justify='space-between' align='middle'>
          <Col span={12} style={{ textAlign: 'left' }}>
            <Button type='primary' onClick={this.add}>
              新增
            </Button>
          </Col>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Search
              placeholder="请输入菜单名称进行搜索"
              onSearch={this.searchChange}
              style={{ width: 240 }}
              allowClear={true}
            />
          </Col>
        </Row>
        <div className='inner-content' style={{ marginTop: '10px' }}>
          <MenuList
            data={this.state.menu}
            edit={this.edit}
            queryList={this.queryList}
            searchName={this.state.searchName}
            expandedRowKeys={this.state.expandedRowKeys} />
        </div>
      </div>
    );
  }
}

export default MenuConfig;
